package com.xysq.util;


import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;

import com.xysq.lemon.R;

import java.io.UnsupportedEncodingException;
import java.math.RoundingMode;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

public class UseUtil {
/*

    public static SpannableString setCashPriceText(Context context, String string) {
        int index1 = string.indexOf("变");
        int index2 = string.indexOf("立");
        int textColor = context.getResources().getColor(R.color.text_normal_coupon);
        SpannableString style = new SpannableString(string);
        style.setSpan(new ForegroundColorSpan(textColor),
                index1, index1 + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        style.setSpan(new ForegroundColorSpan(textColor),
                index2, index2 + 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        style.setSpan(new AbsoluteSizeSpan(UseUtil.spToPx(context, 14)), index1,
                index1 + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        style.setSpan(new AbsoluteSizeSpan(UseUtil.spToPx(context, 14)), index2,
                index2 + 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return style;
    }

    */
/**
 * 现金券显示价格样式（新）
 *//*

    public static SpannableString getCashPrice(Context context, double oldPrice, double newPrice) {
        StringBuilder builder = new StringBuilder();
        builder.append(handlePrice(newPrice)).append("元").append(" ").append(handlePrice(oldPrice)).append("元");
        int start = 0;
        int middle = builder.indexOf(" ") + 1;
        int end = builder.length();
        SpannableString string = new SpannableString(builder);
        */
/*改变文字的大小*//*

        string.setSpan(new AbsoluteSizeSpan(spToPx(context, 20)), start, middle, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        string.setSpan(new AbsoluteSizeSpan(spToPx(context, 14)), middle, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        */
/*给文字设置删除线*//*

        string.setSpan(new StrikethroughSpan(), middle, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        */
/*改变文字的颜色*//*

        int textOrange = context.getResources().getColor(R.color.bg_tab_normal);
        int textGray = context.getResources().getColor(R.color.text_normal_coupon);
        string.setSpan(new ForegroundColorSpan(textOrange), start, middle, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        string.setSpan(new ForegroundColorSpan(textGray), middle, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return string;
    }

    public static SpannableString setDiscountPriceText(Context context, String string) {
        int length = string.length();
        int index = string.indexOf("(");
        int textColor = context.getResources().getColor(R.color.text_normal_coupon);
        SpannableString style = new SpannableString(string);
        style.setSpan(new ForegroundColorSpan(textColor),
                index, length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        style.setSpan(new AbsoluteSizeSpan(UseUtil.spToPx(context, 14)), index,
                length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return style;
    }

    public static SpannableString getDiscountPrice(Context context, double discount, double miniAmount) {
        discount = discount * 0.1;
        StringBuilder builder = new StringBuilder();
        int textOrange = context.getResources().getColor(R.color.bg_tab_normal);
        int textGray = context.getResources().getColor(R.color.text_normal_coupon);
        SpannableString string;
        if (miniAmount > 0) {
            builder.append("满").append(handlePrice(miniAmount)).append("元享").append(handlePrice(discount)).append("折");
            int index = builder.indexOf("元") + 1;
            string = new SpannableString(builder);
            */
/*改变文字的颜色*//*

            int size = string.length();
            string.setSpan(new ForegroundColorSpan(textGray), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            string.setSpan(new ForegroundColorSpan(textOrange), 1, index, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            string.setSpan(new ForegroundColorSpan(textGray), index, index + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            string.setSpan(new ForegroundColorSpan(textOrange), index + 1, size - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            string.setSpan(new ForegroundColorSpan(textGray), size - 1, size, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        } else {
            builder.append(handlePrice(discount)).append("折");
            string = new SpannableString(builder);
            */
/*改变文字的颜色*//*

            int size = string.length();
            string.setSpan(new ForegroundColorSpan(textOrange), 0, size - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            string.setSpan(new ForegroundColorSpan(textGray), size - 1, size, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return string;
    }

    public static SpannableString setVoucherPriceText(Context context, String string) {
        int textColor = context.getResources().getColor(R.color.text_normal_coupon);
        SpannableString style = new SpannableString(string);
        style.setSpan(new ForegroundColorSpan(textColor),
                0, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        style.setSpan(new AbsoluteSizeSpan(UseUtil.spToPx(context, 14)), 0,
                2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return style;
    }

    public static SpannableString getVoucherPrice(Context context, double voucher, double miniAmount) {
        StringBuilder builder = new StringBuilder();
        int textOrange = context.getResources().getColor(R.color.bg_tab_normal);
        int textGray = context.getResources().getColor(R.color.text_normal_coupon);
        SpannableString string;
        if (miniAmount > 0) {
            builder.append("满").append(handlePrice(miniAmount)).append("元减").append(handlePrice(voucher)).append("元");
            int index = builder.indexOf("元") + 1;
            string = new SpannableString(builder);
            */
/*改变文字的颜色*//*

            int size = string.length();
            string.setSpan(new ForegroundColorSpan(textGray), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            string.setSpan(new ForegroundColorSpan(textOrange), 1, index, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            string.setSpan(new ForegroundColorSpan(textGray), index, index + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            string.setSpan(new ForegroundColorSpan(textOrange), index + 1, size, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        } else {
            builder.append("立减").append(handlePrice(voucher)).append("元");
            string = new SpannableString(builder);
            */
/*改变文字的颜色*//*

            int size = string.length();
            string.setSpan(new ForegroundColorSpan(textGray), 0, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            string.setSpan(new ForegroundColorSpan(textOrange), 2, size, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return string;
    }

    public static SpannableString setAccountMoneyPriceText(Context context, String string) {
        int index_start = string.indexOf("(") + 1;
        int index_end = string.indexOf(")");
        int textColor = context.getResources().getColor(R.color.bg_tab_normal);
        SpannableString style = new SpannableString(string);
        style.setSpan(new ForegroundColorSpan(textColor),
                index_start, index_end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return style;
    }

    public static SpannableString setMoneyNotEnoughText(Context context, String string) {
        int index_start = string.indexOf("(") + 1;
        int index_end = string.indexOf(")");
        int length = string.length();
        int textColor = context.getResources().getColor(R.color.bg_tab_normal);
        int showColor = context.getResources().getColor(R.color.text_normal_coupon_red);
        SpannableString style = new SpannableString(string);
        style.setSpan(new ForegroundColorSpan(textColor),
                index_start, index_end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        style.setSpan(new ForegroundColorSpan(showColor),
                index_end + 1, length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return style;
    }

    public static SpannableString setCartMoneyText(Context context, String string) {
        int index_start = string.indexOf("计") + 1;
        int index_end = string.indexOf("元");
        int textColor = context.getResources().getColor(R.color.bg_tab_normal);
        SpannableString style = new SpannableString(string);
        style.setSpan(new ForegroundColorSpan(textColor),
                index_start, index_end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        style.setSpan(new AbsoluteSizeSpan(UseUtil.spToPx(context, 18)), index_start,
                index_end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return style;
    }

    */

/*

    public static String getGainPrice(double oldPrice, double newPrice) {
        double gainPrice = oldPrice - newPrice;
        return handlePrice(gainPrice);
    }

    private static String getSHA1Text(Context context, String string) throws
            NoSuchAlgorithmException, UnsupportedEncodingException {
        String secret = "aa5f6e9c5ee7e0a2904bcafc5130e88e";
        StringBuilder builder = new StringBuilder();
        String builderString = builder.append(secret).append(string).append(secret)
                .toString();
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(builderString.getBytes("UTF-8"), 0, builder.length());
        byte[] result = md.digest();
        StringBuilder buffer = new StringBuilder();
        for (byte b : result) {
            int i = b & 0xff;
            if (i < 0xf) {
                buffer.append(0);
            }
            buffer.append(Integer.toHexString(i));
        }

        return buffer.toString().toUpperCase();
    }

    // 普通Json数据解析
    public static Inmessage parseJson(String strResult) {
        Inmessage message = new Inmessage();
        try {
            JSONObject jsonObj = new JSONObject(strResult);
            //message.setTitle(jsonObj.getString("title"));
            message.setContent(jsonObj.getString("content"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return message;
    }

    public static int setCouponLabel(ModelType modelType) {
        switch (modelType) {
            default:
            case CASH:
                return R.drawable.ic_cash_coupon;
            case VOUCHER:
                return R.drawable.ic_voucher_coupon;
            case DISCOUNT:
                return R.drawable.ic_discount_coupon;
        }
    }


    public static String handlePrice(double price) {
        DecimalFormat decimalFormat = new DecimalFormat("##.##");
        decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
        return decimalFormat.format(price);
    }

    public static String handleNumber(float number, String flag) {
        DecimalFormat decimalFormat = new DecimalFormat(flag);
        return decimalFormat.format(number);
    }

    public static int dpToPx(Context context, float dpValue) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue,
                context.getResources().getDisplayMetrics());
    }

    public static int spToPx(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }
*/

    public static String hideName(String name){
        int length = name.length();
        if (length == 1) {
            return name;
        } else {
            String front = name.substring(0, 1);
            String behind = name.substring(2, length);
            return front + "*" + behind;
        }
    }
    public static String timeToDate(long time) {
        Log.d("test", new Date(time).toString());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(new Date(time));
    }

    public static String timeToDetailDate(long time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(new Date(time));
    }

    public static String getCurrentDate() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        return format.format(new Date());
    }

    public static int dp2Px(Context context, float dp) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    public static int px2Dp(Context context, float px) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (px / scale + 0.5f);
    }

    public static String handlePrice(double price) {
        DecimalFormat decimalFormat = new DecimalFormat("##.##");
        decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
        return decimalFormat.format(price);
    }

    public static String formatPrice(double price) {
        String result = String.format("%.2f", price);
        return  result;
    }

    public static int getScreenWidth(Activity activity) {
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }

    public static int getScreenHeight(Activity activity) {
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.heightPixels;
    }

    public static String handleWithStar(String phone) {
        String front = phone.substring(0, 3);
        String behind = phone.substring(7, 11);
        return front + "****" + behind;
    }

    public static boolean detectNetwork(Activity act) {
        ConnectivityManager manager = (ConnectivityManager) act
                .getApplicationContext().getSystemService(
                        Context.CONNECTIVITY_SERVICE);
        if (manager == null) {
            return false;
        }
        NetworkInfo networkinfo = manager.getActiveNetworkInfo();
        if (networkinfo == null || !networkinfo.isAvailable()) {
            return false;
        }
        return true;
    }

    public static String processUrl(String url, Map<String, String> params) {
        String picUrl[] = splitUrl(url);
        String baseUrl = picUrl[0];
        String paramString = picUrl[1];
        splitParams(paramString, params);
        return  baseUrl;
    }

    public static void splitParams(String paramString, Map<String, String> params) {
        String divider = "&";
        String[] separateParam = paramString.split(divider);

        for(int i = 0;i<separateParam.length;i++){
            splitSingleParam(separateParam[i], params);

        }
    }

    public static void splitSingleParam(String singleParam, Map<String, String> params) {
        String divider = "=";
        String[] mapParam = singleParam.split(divider);
        try {
            params.put(mapParam[0], URLDecoder.decode(mapParam[1], "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public static String[] splitUrl(String picUrls) {
        String divider = "\\?";
        String[] picUrl = picUrls.split(divider);
        return picUrl;
    }
    public static String selectName(String commentNickName, String commentUserName, String commentUserPhoneNum) {
        if(!TextUtils.isEmpty(commentNickName)){
            return commentNickName;
        }
        if(!TextUtils.isEmpty(commentUserName)){
            return hideName(commentUserName);
        }
        if(!TextUtils.isEmpty(commentUserPhoneNum)) {
            return handleWithStar(commentUserPhoneNum);
        }
        return "匿名";
    }

    public static String selectName(String commentUserName, String commentUserPhoneNum) {
        if (!TextUtils.isEmpty(commentUserName)) {
            return commentUserName;
        }
        return handleWithStar(commentUserPhoneNum);
    }

    public static String checkTailSemicolon(String picUrl) {
        String lastCharacter = picUrl.substring(picUrl.length() - 1, picUrl.length());
        if(lastCharacter.equals(";")){
            return picUrl;
        }else {
            return picUrl + ";";
        }
    }

    public static String[] getDates() {
        String yearsArray[] = new String[11];
        Calendar year = Calendar.getInstance();
        for(int i=10;i>=0;i--){
            yearsArray[i] = String.valueOf(year.get(Calendar.YEAR) - i);
        }
        return yearsArray;
    }

    public static String checkSex(String sexNumber, Context context) {
        if(sexNumber.equals("1")){
            return context.getResources().getString(R.string.txt_male);
        }
        return context.getResources().getString(R.string.txt_female);
    }
}
